package com.wetao.trackscreendemo;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.target.CustomTarget;
import com.bumptech.glide.request.transition.Transition;
import com.wetao.trackscreendemo.voicerecorder.EMError;
import com.wetao.trackscreendemo.voicerecorder.VoiceRecorder;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

import cn.forward.androids.utils.LogUtil;
import cn.hzw.doodle.DoodleOnTouchGestureListener;
import cn.hzw.doodle.DoodleParams;
import cn.hzw.doodle.DoodlePen;
import cn.hzw.doodle.DoodleTouchDetector;
import cn.hzw.doodle.DoodleView;
import cn.hzw.doodle.IDoodleListener;
import cn.hzw.doodle.core.IDoodle;
import cn.hzw.doodle.core.IDoodleItemListener;
import cn.hzw.doodle.core.IDoodleSelectableItem;
import cn.hzw.doodle.core.IDoodleTouchDetector;

import static com.wetao.trackscreendemo.voicerecorder.VoiceRecorderView.HANDLER_VOLUME;

public class RecordActivity extends AppCompatActivity  implements View.OnClickListener{

    private static final int HANDLER_TEST_DELAY_TIME = 900;
    private static final int HANDLER_TRACK_DRAWING = 901;
    private static final int HANDLER_TRACK_UNDO = 902;
    private static final int HANDLER_TRACK_LARGE_JUMPING = 903;
    private static final int HANDLER_AGAIN_RECORD_OR_PLAY= 904;
    private boolean isTest = true;
    private String mobile = "mobile"; //账号手机号，需要从后台拿
    private String keshi = "keshi"; //课时id，需要从后台拿
    private String shiti = "shiti"; //试题id，需要从后台拿
    private String test60shiti = "test60shiti"; //试题id，需要从后台拿

    private boolean hasFirstRecord = false;


    private boolean isEraser = false;
    private boolean isWhiteboard = false;
    private boolean isGliding = false;
    private int mWhiteboardMaxPage = 10;
    private int fl_width;
    private int fl_height;

    private boolean isPx30Eink = false;




    TextView tv_recordStatus;
    TextView tv_recordTime;
    TextView tv_recordVol;
    FrameLayout fl_doodle;
    ImageView iv_doodle_prev;
    ImageView iv_doodle_next;
    TextView btn_doodle_num;
    Button btn_eraser;
    Button btn_Whiteboard;

    protected PowerManager.WakeLock wakeLock;

    private String voiceFilePath;
    protected int mMaxTime = 1 * 60 * 60 * 1000;
    protected VoiceRecorder voiceRecorder;
    private int mRecorderTime = 0;

    private int mDoodleImageIndex = 0;
    private List<String> mDoodleImagePath = new ArrayList<>();
    private List<Bitmap> mDoodle_bitmap_list = new ArrayList<>();
    private List<DoodleParams> mDoodleParams_list = new ArrayList<>();
    private List<IDoodle> mDoodle_list = new ArrayList<>();
    private List<DoodleView> mDoodleView_list = new ArrayList<>();
    private List<DoodleOnTouchGestureListener> mDoodleTouchGestureListener_list = new ArrayList<>();

    private int mWhiteboard_DoodleImageIndex = 0;
    private String mWhiteboard_DoodleImagePath;
    private Bitmap mWhiteboard_Doodle_bitmap;
    private List<DoodleParams>mWhiteboard_DoodleParams_list = new ArrayList<>();
    private List<IDoodle> mWhiteboard_Doodle_list = new ArrayList<>();
    private List<DoodleView> mWhiteboard_DoodleView_list = new ArrayList<>();
    private List<DoodleOnTouchGestureListener> mWhiteboard_DoodleTouchGestureListener_list = new ArrayList<>();


    private String trackFilePath;
    private int trackId = 0;
    private List<TrackBean> trackBeanList = new ArrayList<>();



    private MyHandler handler;
    static class MyHandler extends Handler {
        WeakReference<RecordActivity> weakReference;
        public MyHandler(RecordActivity activity) {
            weakReference = new WeakReference(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            if(weakReference.get() == null) {
                return;
            }
            RecordActivity activity = weakReference.get();
            if(msg.what == HANDLER_VOLUME) {
                activity.onSetVolume(msg.arg1, msg.arg2);
            } else if(msg.what == HANDLER_AGAIN_RECORD_OR_PLAY) {

                if(msg.arg1 == 1) {
                    activity.startRecording();
                }
            }
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_record);

        initView();
        initData();
    }

    private void initView() {
        tv_recordStatus = findViewById(R.id.tv_recordStatus);
        tv_recordTime = findViewById(R.id.tv_recordTime);
        tv_recordVol = findViewById(R.id.tv_recordVol);
        fl_doodle = findViewById(R.id.fl_doodle);
        iv_doodle_prev = findViewById(R.id.iv_doodle_prev);
        iv_doodle_next = findViewById(R.id.iv_doodle_next);
        btn_doodle_num = findViewById(R.id.btn_doodle_num);
        btn_eraser = findViewById(R.id.btn_eraser);
        btn_Whiteboard = findViewById(R.id.btn_Whiteboard);


        Button btn_startRecord = findViewById(R.id.btn_startRecord);
        Button btn_pauseRecord = findViewById(R.id.btn_pauseRecord);
        Button btn_resumeRecord = findViewById(R.id.btn_resumeRecord);
        Button btn_completeRecord = findViewById(R.id.btn_completeRecord);
        Button btn_againRecord = findViewById(R.id.btn_againRecord);
        Button btn_revoke = findViewById(R.id.btn_revoke);
        Button btn_unrevoke = findViewById(R.id.btn_unrevoke);
        btn_startRecord.setOnClickListener(this);
        btn_pauseRecord.setOnClickListener(this);
        btn_resumeRecord.setOnClickListener(this);
        btn_completeRecord.setOnClickListener(this);
        btn_againRecord.setOnClickListener(this);
        btn_eraser.setOnClickListener(this);
        btn_Whiteboard.setOnClickListener(this);
        btn_revoke.setOnClickListener(this);
        btn_unrevoke.setOnClickListener(this);

        iv_doodle_prev.setOnClickListener(this);
        iv_doodle_next.setOnClickListener(this);


    }
    private void initData() {

        wakeLock = ((PowerManager) getSystemService(Context.POWER_SERVICE)).newWakeLock(
                PowerManager.SCREEN_DIM_WAKE_LOCK, "voice");

        handler = new MyHandler(this);

        String mDeviceProductName = DeviceInfoUtils.getDeviceProduct();
        LogUtil.i("设备名：" + mDeviceProductName);
        if(PlayService_2.PX30_EINK.equals(mDeviceProductName)) {
            isPx30Eink = true;
        }


        voiceRecorder = new VoiceRecorder(handler);

        mDoodleImagePath.add("/sdcard/Android/data/com.wetao.trackscreendemo/files/mobile/audiotrack/keshi/shiti/pic_0.png");
        mDoodleImagePath.add("/sdcard/Android/data/com.wetao.trackscreendemo/files/mobile/audiotrack/keshi/shiti/pic_1.png");
        mDoodleImagePath.add("/sdcard/Android/data/com.wetao.trackscreendemo/files/mobile/audiotrack/keshi/shiti/pic_2.png");
        mDoodleImagePath.add("/sdcard/Android/data/com.wetao.trackscreendemo/files/mobile/audiotrack/keshi/shiti/pic_3.png");
        mDoodleImagePath.add("/sdcard/Android/data/com.wetao.trackscreendemo/files/mobile/audiotrack/keshi/shiti/pic_4.png");
        mDoodleImagePath.add("/sdcard/Android/data/com.wetao.trackscreendemo/files/mobile/audiotrack/keshi/shiti/pic_6.png");
        mDoodleImagePath.add("/sdcard/Android/data/com.wetao.trackscreendemo/files/mobile/audiotrack/keshi/shiti/pic_7.png");
        mWhiteboard_DoodleImagePath = "/sdcard/Android/data/com.wetao.trackscreendemo/files/mobile/audiotrack/keshi/shiti/pic_5.png";

        fl_doodle.post(new Runnable() {
            @Override
            public void run() {
                fl_width = fl_doodle.getMeasuredWidth();
                fl_height = fl_doodle.getMeasuredHeight();
                LogUtil.i("fl_doodle的宽：" + fl_width + ", 高" + fl_height);
            }
        });

        downLoadImg(false);

        if(isPx30Eink) {
            ComUtil.setWindowEpdMode(this, 2);
        }

    }

    @Override
    protected void onStop() {
        super.onStop();
        cancelRecording();

    }

    @Override
    protected void onDestroy() {
        if(handler != null) {
            handler.removeCallbacksAndMessages(null);
            handler = null;
        }
        super.onDestroy();


        if(isPx30Eink) {
            ComUtil.setWindowEpdMode(this, 0);
        }
    }

    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.btn_startRecord) {
            if(isTest) {
                fileOperate();
            }
            if(hasFirstRecord) {
                again_recording_or_play(false);
            } else {
                hasFirstRecord = true;
                startRecording();
            }

        } else if(view.getId() == R.id.btn_pauseRecord) {
            pauseRecording();
        } else if(view.getId() == R.id.btn_resumeRecord) {
            resumeRecording();
        } else if(view.getId() == R.id.btn_completeRecord) {
            completeRecord();
        } else if(view.getId() == R.id.btn_againRecord) {
            if(isTest) {
                fileOperate();
            }
            again_recording_or_play(false);
        } else if(view.getId() == R.id.btn_eraser) {
            switchEraser();
        } else if(view.getId() == R.id.btn_Whiteboard) {
            switchWhiteboard(false);
        } else if(view.getId() == R.id.btn_revoke) {
            if (!isWhiteboard && !mDoodle_list.get(mDoodleImageIndex).undo()) {
                LogUtil.i("无法再撤销");
            }else if (isWhiteboard && !mWhiteboard_Doodle_list.get(mWhiteboard_DoodleImageIndex).undo()) {
                LogUtil.i("无法再撤销");
            } else {
                writeActionToFile("ACTION_UNDO");
            }
        } else if(view.getId() == R.id.btn_unrevoke) {
            if (!isWhiteboard && !mDoodle_list.get(mDoodleImageIndex).redo(1)) {
                LogUtil.i("无法再反撤销");
            } else if (isWhiteboard && !mWhiteboard_Doodle_list.get(mWhiteboard_DoodleImageIndex).redo(1)) {
                LogUtil.i("无法再反撤销");
            }else {
                writeActionToFile("ACTION_REDO");
            }
        } else if(view.getId() == R.id.iv_doodle_prev) {
            prevPage();
        } else if(view.getId() == R.id.iv_doodle_next) {
            nextPage();
        }
    }


    private boolean  fileOperate() {
        if (!FileUtils.isSdcardExist()) {
            LogUtil.i( "SD卡不存在");
            return false;
        }
        String dirPath = getExternalFilesDir(null).getAbsolutePath();

        String voiceDirPath = dirPath + File.separator + mobile + File.separator + "audiotrack" + File.separator + keshi + File.separator + shiti;
        File voiceDir = new File(voiceDirPath);
        if (!voiceDir.exists()) {
            boolean mkdirs = voiceDir.mkdirs();
            if (!mkdirs) {
                LogUtil.e("创建失败voiceDir：" + mkdirs);
                return false;
            } else {
                LogUtil.i("创建成功voiceDir");
            }
        }

        voiceFilePath = voiceDir + File.separator + "11.mp3";
        trackFilePath = voiceDir + File.separator + "track.txt";
        return true;
    }


    public void startRecording() {
        if(voiceRecorder.getRecordStatus() != VoiceRecorder.VOICE_RECORDER_IDE
                && voiceRecorder.getRecordStatus() != VoiceRecorder.VOICE_RECORDER_COMPLETE) {
            LogUtil.i("不能点两次开始录制");
            return;
        }
        if(!fileOperate()) {
            return;
        }

        File trackFile = new File(trackFilePath);
        if(trackFile.exists()) {
            trackFile.delete();
        }

        voiceRecorder.setVoiceFilePath(voiceFilePath);

        try {
            onVoiceStartRecording();
            wakeLock.acquire();
            voiceRecorder.startRecording(this);
        } catch (Exception e) {
            e.printStackTrace();
            if (wakeLock.isHeld())
                wakeLock.release();
            if (voiceRecorder != null)
                voiceRecorder.discardRecording();
            onVoiceRecordFail();
            LogUtil.i("录音失败");
            return;
        }
    }

    private void pauseRecording() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            if(voiceRecorder.getRecordStatus() != VoiceRecorder.VOICE_RECORDER_START) {
                LogUtil.i("只有在正在录制时，才能暂停");
                return;
            }
            onVoicePauseRecording();
            voiceRecorder.pauseRecording();
        }
    }

    private void resumeRecording() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            if(voiceRecorder.getRecordStatus() != VoiceRecorder.VOICE_RECORDER_PAUSE) {
                LogUtil.i("只有在暂停录制时，才能恢复录制");
                return;
            }
            onVoiceResumeRecording();
            voiceRecorder.resumeRecording();
        }
    }

    private void completeRecord() {
        if(voiceRecorder.getRecordStatus() == VoiceRecorder.VOICE_RECORDER_START
                || voiceRecorder.getRecordStatus() == VoiceRecorder.VOICE_RECORDER_PAUSE) {
            try {
                int length = stopRecoding();
                if (length > 0) {
                    onVoiceRecordComplete(getVoiceFilePath(), length);
                } else if (length == EMError.FILE_INVALID) {
                    onVoiceRecordFail();
                    LogUtil.i( "没有录音权限，录音失败");
                } else {
                    onVoiceRecordFail();
                    LogUtil.i("录音时间太短，录音失败");
                }
            } catch (Exception e) {
                e.printStackTrace();
                // Toast.makeText(context, R.string.send_failure_please, Toast.LENGTH_SHORT).show();
            }
        } else {
            LogUtil.i( "只有正在录制或者暂停录制时，才能点击完成录制");
        }

    }

    private void cancelRecording() {
        discardRecording();
    }

    private void again_recording_or_play(boolean isPlay) {

        isEraser = false;
        isWhiteboard = false;
        isGliding = false;

        fl_doodle.removeAllViews();

        voiceRecorder.stopRecoding();

        mDoodleImageIndex = 0;
        mDoodle_bitmap_list = new ArrayList<>();
        mDoodleParams_list = new ArrayList<>();
        mDoodle_list = new ArrayList<>();
        mDoodleView_list = new ArrayList<>();
        mDoodleTouchGestureListener_list = new ArrayList<>();

        mWhiteboard_DoodleImageIndex = 0;
        mWhiteboard_Doodle_bitmap = null;
        mWhiteboard_DoodleParams_list = new ArrayList<>();
        mWhiteboard_Doodle_list = new ArrayList<>();
        mWhiteboard_DoodleView_list = new ArrayList<>();
        mWhiteboard_DoodleTouchGestureListener_list = new ArrayList<>();


        trackId = 0;
        trackBeanList = new ArrayList<>();

        downLoadImg(false);

        Message msg = handler.obtainMessage();
        msg.what = HANDLER_AGAIN_RECORD_OR_PLAY;
        msg.arg1 = isPlay?2:1;
        handler.sendMessageDelayed(msg, 500);



    }

    private void onVoiceStartRecording() {
        tv_recordStatus.setText("开始录音");
        setSupportDoodle(true);
    }
    private void onVoicePauseRecording() {
        tv_recordStatus.setText("暂停录音");
        setSupportDoodle(false);
    }
    private void onVoiceResumeRecording() {
        tv_recordStatus.setText("恢复录音");
        setSupportDoodle(true);
    }

    private void onVoiceRecordComplete(String voiceFilePath, int voiceTimeLength) {
        mRecorderTime = voiceTimeLength;
        tv_recordTime.setText("时间：" + (int)(voiceTimeLength/1000));
        tv_recordStatus.setText("完成录音");
        setSupportDoodle(false);
    }

    private void onVoiceRecordFail() {
        tv_recordStatus.setText("录音失败");
        setSupportDoodle(false);
    }

    private void setSupportDoodle(boolean isSupport) {
        if(!isWhiteboard && mDoodleTouchGestureListener_list.get(mDoodleImageIndex) != null) {
            mDoodleTouchGestureListener_list.get(mDoodleImageIndex).setSupportDoodle(isSupport);
        } else if(isWhiteboard && mWhiteboard_DoodleTouchGestureListener_list.get(mWhiteboard_DoodleImageIndex) != null) {
            mWhiteboard_DoodleTouchGestureListener_list.get(mWhiteboard_DoodleImageIndex).setSupportDoodle(isSupport);
        }
    }
    private void onSetVolume(int volume, int second) {
        mRecorderTime = second;
        tv_recordTime.setText("时间：" + (int)(second / 1000));
        tv_recordVol.setText("音量：" + volume);

        if(second >= mMaxTime) {
            completeRecord();
        }
    }

    public void discardRecording() {
        if (wakeLock.isHeld())
            wakeLock.release();
        try {
            // stop recording
            if (voiceRecorder.getRecordStatus() == VoiceRecorder.VOICE_RECORDER_START
                    || voiceRecorder.getRecordStatus() == VoiceRecorder.VOICE_RECORDER_PAUSE) {
                voiceRecorder.discardRecording();
                onVoiceRecordFail();
            }
        } catch (Exception e) {
        }
    }

    public int stopRecoding() {
        if (wakeLock.isHeld())
            wakeLock.release();
        return voiceRecorder.stopRecoding();
    }

    public String getVoiceFilePath() {
        return voiceRecorder.getVoiceFilePath();
    }


    public void setVoiceFilePath(String voiceFilePath) {
        voiceRecorder.setVoiceFilePath(voiceFilePath);
    }

    private void downLoadImg(final boolean isPlay) {
        final String f_url = isWhiteboard ? mWhiteboard_DoodleImagePath : mDoodleImagePath.get(mDoodleImageIndex);
        isGliding = true;
        Glide.with(this).asBitmap().load(f_url).skipMemoryCache(true).diskCacheStrategy(DiskCacheStrategy.NONE)
                .into(new CustomTarget<Bitmap>() {
                    @Override
                    public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                        isGliding = false;
                        Thread thread1 = getMainLooper().getThread();
                        Thread thread2 = Thread.currentThread();

                        LogUtil.i("-----doodle----glide主线程ID: "+thread1.getId() );
                        LogUtil.i("-----doodle----glide当前线程ID: "+thread2.getId() );

                        LogUtil.i("Glde图片-成功 url = " + f_url);
                        if(isWhiteboard) {
                            mWhiteboard_Doodle_bitmap = resource;
                        } else {
                            mDoodle_bitmap_list.add(resource);
                        }


                        initDoodleData(isPlay);
                    }

                    @Override
                    public void onLoadFailed(@Nullable Drawable errorDrawable) {
                        super.onLoadFailed(errorDrawable);
                        isGliding = false;
                        LogUtil.e("Glde图片-失败 url = " + f_url);
                    }

                    @Override
                    public void onLoadCleared(@Nullable Drawable placeholder) {

                    }
                });
    }

    private void set_btn_doodle_num(){
        if(isWhiteboard) {
            btn_doodle_num.setText((mWhiteboard_DoodleImageIndex + 1) + "/" + mWhiteboard_DoodleView_list.size());
            if(mWhiteboard_DoodleImageIndex >= mWhiteboard_DoodleView_list.size() - 1){
                iv_doodle_next.setImageResource(R.drawable.ic_collapse_selected);
            } else {
                iv_doodle_next.setImageResource(R.drawable.marking_doodle_next);
            }
        } else {
            btn_doodle_num.setText((mDoodleImageIndex + 1) + "/" + mDoodleImagePath.size());
            iv_doodle_next.setImageResource(R.drawable.marking_doodle_next);
        }
    }

    private void initDoodleData(boolean isPlay) {
        //fl_doodle.removeAllViews();
        DoodleParams mDoodleParams = new DoodleParams();
        if(isWhiteboard) {
            mDoodleParams.mImagePath = mWhiteboard_DoodleImagePath;
            mDoodleParams.mSavePath = mWhiteboard_DoodleImagePath;
        } else {
            mDoodleParams.mImagePath = mDoodleImagePath.get(mDoodleImageIndex);
            mDoodleParams.mSavePath = mDoodleImagePath.get(mDoodleImageIndex);
        }
        mDoodleParams.mSavePathIsDir = false;
        mDoodleParams.mIsDrawableOutside = false;


        /*
        Whether or not to optimize drawing, it is suggested to open, which can optimize the drawing speed and performance.
        Note: When item is selected for editing after opening, it will be drawn at the top level, and not at the corresponding level until editing is completed.
        是否优化绘制，建议开启，可优化绘制速度和性能.
        注意：开启后item被选中编辑时时会绘制在最上面一层，直到结束编辑后才绘制在相应层级
         */

        IDoodle mDoodle = null;
        DoodleView mDoodleView = null;
        mDoodle = mDoodleView = new DoodleViewWrapper(this, isWhiteboard ? mWhiteboard_Doodle_bitmap : mDoodle_bitmap_list.get(mDoodleImageIndex), mDoodleParams.mOptimizeDrawing, new IDoodleListener() {
            @Override
            public void onSaved(IDoodle doodle, Bitmap bitmap, Runnable callback) { // 保存图片为jpg格式
                LogUtil.i("-----doodle----onSaved");
                Thread thread1 = getMainLooper().getThread();
                Thread thread2 = Thread.currentThread();

                LogUtil.i("-----doodle----doodleViewWrapper主线程ID: "+thread1.getId() );
                LogUtil.i("-----doodle----doodleViewWrapper当前线程ID: "+thread2.getId() );
            }

            @Override
            public void onReady(IDoodle doodle) {
                LogUtil.i("-----doodle----onReady");
            }
        });

        DoodleOnTouchGestureListener mTouchGestureListener = new DoodleOnTouchGestureListener(mDoodleView, new DoodleOnTouchGestureListener.ISelectionListener() {

            IDoodleItemListener mIDoodleItemListener = new IDoodleItemListener() {
                @Override
                public void onPropertyChanged(int property) {

                }
            };

            @Override
            public void onSelectedItem(IDoodle doodle, IDoodleSelectableItem selectableItem, boolean selected) {

            }

            @Override
            public void onCreateSelectableItem(IDoodle doodle, float x, float y) {

            }

            @Override
            public void onCallScrollBegin(MotionEvent e) {
                writeEventTofile(e);
            }

            @Override
            public void onCallScrollEnd(MotionEvent e) {
                writeEventTofile(e);
            }

            @Override
            public void onCallScroll(MotionEvent e) {
                writeEventTofile(e);
            }
        }) {
            @Override
            public void setSupportScaleItem(boolean supportScaleItem) {
                super.setSupportScaleItem(supportScaleItem);
            }
        };

        mTouchGestureListener.setSupportScale(false); //禁止放大缩小
        if(voiceRecorder.getRecordStatus() != VoiceRecorder.VOICE_RECORDER_START) {
            mTouchGestureListener.setSupportDoodle(false); //禁止涂鸦
        } else {
            mTouchGestureListener.setSupportDoodle(true); //禁止涂鸦
        }
        mTouchGestureListener.setTouchType(DoodleOnTouchGestureListener.TOUCH_TYPE_ALL);
        IDoodleTouchDetector detector = new DoodleTouchDetector(getApplicationContext(), mTouchGestureListener);
        mDoodleView.setDefaultTouchDetector(detector);

        mDoodle.setIsDrawableOutside(mDoodleParams.mIsDrawableOutside);
        fl_doodle.addView(mDoodleView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        mDoodle.setDoodleMinScale(mDoodleParams.mMinScale);
        mDoodle.setDoodleMaxScale(mDoodleParams.mMaxScale);
        //mDoodle.setSize(2);

        if(isWhiteboard) {
            mWhiteboard_DoodleParams_list.add(mDoodleParams);
            mWhiteboard_Doodle_list.add(mDoodle);
            mWhiteboard_DoodleView_list.add(mDoodleView);
            mWhiteboard_DoodleTouchGestureListener_list.add(mTouchGestureListener);
        } else {
            mDoodleParams_list.add(mDoodleParams);
            mDoodle_list.add(mDoodle);
            mDoodleView_list.add(mDoodleView);
            mDoodleTouchGestureListener_list.add(mTouchGestureListener);
        }

        set_btn_doodle_num();

    }

    /**
     * 包裹DoodleView，监听相应的设置接口，以改变UI状态
     */
    private class DoodleViewWrapper extends DoodleView {

        public DoodleViewWrapper(Context context, Bitmap bitmap, boolean optimizeDrawing, IDoodleListener listener) {
            super(context, bitmap, optimizeDrawing, listener);
        }
    }

    private void prevPage() {
        if(voiceRecorder.getRecordStatus() != VoiceRecorder.VOICE_RECORDER_START) {
            LogUtil.i("只有在录制过程中才可以切换页");
            return;
        }

        switchPage(false, false);
    }

    private void nextPage() {
        if(voiceRecorder.getRecordStatus() != VoiceRecorder.VOICE_RECORDER_START) {
            LogUtil.i("只有在录制过程中才可以切换页");
            return;
        }
        switchPage(true, false);
    }

    private void switchPage(final boolean isNext, final boolean isPlay) {
        if(isGliding) {
            LogUtil.i("正在加载图片，请稍后");
            return;
        }

        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                switchPage_real(isNext, isPlay);
            }
        });
    }

    private void switchPage_real(boolean isNext, boolean isPlay) {
        if(isNext) {
            if(isWhiteboard) {
                if (mWhiteboard_DoodleImageIndex >= mWhiteboard_DoodleView_list.size() - 1
                        && mWhiteboard_DoodleView_list.size() >= mWhiteboardMaxPage) {
                    LogUtil.i("已经是最后一页，无法下一页");
                    return;
                }
            } else {
                if (mDoodleImageIndex >= mDoodleImagePath.size() - 1) {
                    LogUtil.i("已经是最后一页，无法下一页");
                    return;
                }
            }
            if(!isPlay) {
                if(isEraser) {
                    switchEraser();
                }
                writeActionToFile("ACTION_NEXT_PAGE");
            }
            if(isWhiteboard) {
                mWhiteboard_DoodleImageIndex++;
            } else {
                mDoodleImageIndex++;
            }
        } else {
            if(isWhiteboard) {
                if (mWhiteboard_DoodleImageIndex == 0) {
                    LogUtil.i("已经是第一页，无法上一页");
                    return;
                }
            } else {
                if (mDoodleImageIndex == 0) {
                    LogUtil.i("已经是第一页，无法上一页");
                    return;
                }
            }

            if(!isPlay) {
                if(isEraser) {
                    switchEraser();
                }
                writeActionToFile("ACTION_PREV_PAGE");
            }
            if(isWhiteboard) {
                mWhiteboard_DoodleImageIndex--;
            } else {
                mDoodleImageIndex--;
            }
        }
        if(isWhiteboard) {
            for (int i = 0; i < mWhiteboard_DoodleView_list.size(); i++) {
                mWhiteboard_DoodleView_list.get(i).setVisibility(View.GONE);
                mWhiteboard_DoodleTouchGestureListener_list.get(i).setSupportDoodle(false); //禁止涂鸦
            }
            if (mWhiteboard_DoodleImageIndex >= mWhiteboard_DoodleView_list.size()) {
                initDoodleData(isPlay);
            } else {
                mWhiteboard_DoodleView_list.get(mWhiteboard_DoodleImageIndex).setVisibility(View.VISIBLE);
                if(isPlay) {

                } else {
                    mWhiteboard_DoodleTouchGestureListener_list.get(mWhiteboard_DoodleImageIndex).setSupportDoodle(true); //禁止涂鸦
                }

            }
        } else {
            for (int i = 0; i < mDoodleView_list.size(); i++) {
                mDoodleView_list.get(i).setVisibility(View.GONE);
                mDoodleTouchGestureListener_list.get(i).setSupportDoodle(false); //禁止涂鸦
            }
            if (mDoodleImageIndex >= mDoodleView_list.size()) {
                downLoadImg(isPlay); //这个函数中也有drawTrack_pub();
            } else {
                mDoodleView_list.get(mDoodleImageIndex).setVisibility(View.VISIBLE);
                if(isPlay) {

                } else {
                    mDoodleTouchGestureListener_list.get(mDoodleImageIndex).setSupportDoodle(true); //禁止涂鸦
                }

            }
        }

        set_btn_doodle_num();
    }

    private void switchEraser() {
        isEraser = !isEraser;
        if(isEraser) {
            writeActionToFile("ACTION_PEN_ERASER");
            if(isWhiteboard) {
                mWhiteboard_Doodle_list.get(mWhiteboard_DoodleImageIndex).setPen(DoodlePen.ERASER);
            } else {
                mDoodle_list.get(mDoodleImageIndex).setPen(DoodlePen.ERASER);
            }
            btn_eraser.setText("切换到画笔");

        } else {
            writeActionToFile("ACTION_PEN_BRUSH");
            if(isWhiteboard) {
                mWhiteboard_Doodle_list.get(mWhiteboard_DoodleImageIndex).setPen(DoodlePen.BRUSH);
            } else {
                mDoodle_list.get(mDoodleImageIndex).setPen(DoodlePen.BRUSH);
            }
            btn_eraser.setText("切换到橡皮檫");
        }
    }

    private void switchWhiteboard(final boolean isPlay) {
        if(!isPlay && voiceRecorder.getRecordStatus() != VoiceRecorder.VOICE_RECORDER_START) {
            LogUtil.i("只有在正在录制时，才能切换白板");
            return;
        }
        if(isGliding) {
            LogUtil.i("正在加载图片，请稍后");
            return;
        }
        if(isPlay) {

        }
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                switchWhiteboard_real(isPlay);
            }
        });
    }

    private void switchWhiteboard_real(boolean isPlay) {
        if(!isPlay) {
            if (isEraser) {
                switchEraser();
            }
        }
        isWhiteboard = !isWhiteboard;
        set_btn_Whiteboard_text();
        if(!isPlay) {
            writeActionToFile("ACTION_SWITCH_WHITEBOARD");
        }
        if(isWhiteboard) {
            mDoodleView_list.get(mDoodleImageIndex).setVisibility(View.GONE);
            mDoodleTouchGestureListener_list.get(mDoodleImageIndex).setSupportDoodle(false); //禁止涂鸦
            if(mWhiteboard_Doodle_bitmap == null) {
                downLoadImg(isPlay);
            } else {
                mWhiteboard_DoodleView_list.get(mWhiteboard_DoodleImageIndex).setVisibility(View.VISIBLE);
                if(isPlay) {

                } else {
                    mWhiteboard_DoodleTouchGestureListener_list.get(mWhiteboard_DoodleImageIndex).setSupportDoodle(true); //禁止涂鸦
                }
            }
        } else {
            mWhiteboard_DoodleView_list.get(mWhiteboard_DoodleImageIndex).setVisibility(View.GONE);
            mWhiteboard_DoodleTouchGestureListener_list.get(mWhiteboard_DoodleImageIndex).setSupportDoodle(false); //禁止涂鸦

            mDoodleView_list.get(mDoodleImageIndex).setVisibility(View.VISIBLE);
            if(isPlay) {

            } else {
                mDoodleTouchGestureListener_list.get(mDoodleImageIndex).setSupportDoodle(true); //禁止涂鸦
            }

        }

        set_btn_doodle_num();
    }

    private void set_btn_Whiteboard_text() {
        if(isWhiteboard) {
            btn_Whiteboard.setText("切换到试题");
        } else {
            btn_Whiteboard.setText("切换到白板");
        }
    }

    private void writeEventTofile(MotionEvent e) {
        if(!fileOperate()) {
            return;
        }
        if(e != null) {
            String action = "ACTION_DOWN";
            if(e.getAction() == MotionEvent.ACTION_MOVE) {
                action = "ACTION_MOVE";
            } else if(e.getAction() == MotionEvent.ACTION_UP) {
                action = "ACTION_UP";
            }
            trackId++;
            TrackBean trackBean = new TrackBean(trackId, e.getX(), e.getY(), action, mRecorderTime, isWhiteboard ? mWhiteboard_DoodleImageIndex : mDoodleImageIndex, isWhiteboard, fl_width, fl_height);
            lineWriteFile(trackFilePath, JsonUtils.toJson(trackBean));

        }
    }

    private void writeActionToFile(String action) {
        if(!fileOperate()) {
            return;
        }
        trackId++;
        TrackBean trackBean = new TrackBean(trackId, -1, -1, action, mRecorderTime, isWhiteboard ? mWhiteboard_DoodleImageIndex : mDoodleImageIndex, isWhiteboard, fl_width, fl_height);
        lineWriteFile(trackFilePath, JsonUtils.toJson(trackBean));
    }

    private void lineWriteFile(String filePath, String json){
        try {
            FileWriter fw = new FileWriter(new File(filePath), true);
            //写入中文字符时会出现乱码
            BufferedWriter bw=new BufferedWriter(fw);
            //BufferedWriter  bw=new BufferedWriter(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File("E:/phsftp/evdokey/evdokey_201103221556.txt")), "UTF-8")));
            bw.write(json+"\r\n");
            bw.close();
            fw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
